package org.jeecg.modules.wms.inOrder.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.wms.common.constant.CommonWms;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.wms.inOrder.entity.WmsOrderLine;
import org.jeecg.modules.wms.inOrder.entity.WmsOrderHeader;
import org.jeecg.modules.wms.inOrder.vo.WmsOrderHeaderPage;
import org.jeecg.modules.wms.inOrder.service.IWmsOrderHeaderService;
import org.jeecg.modules.wms.inOrder.service.IWmsOrderLineService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 入库单主表
 * @Author: jeecg-boot
 * @Date: 2023-11-13
 * @Version: V1.0
 */
@Api(tags = "入库单主表")
@RestController
@RequestMapping("/inOrder/wmsOrderHeader")
@Slf4j
public class WmsOrderHeaderController {
    @Autowired
    private IWmsOrderHeaderService wmsOrderHeaderService;
    @Autowired
    private IWmsOrderLineService wmsOrderLineService;

    /**
     * 分页列表查询
     *
     * @param wmsOrderHeader
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "入库单主表-分页列表查询")
    @ApiOperation(value = "入库单主表-分页列表查询", notes = "入库单主表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<WmsOrderHeader>> queryPageList(WmsOrderHeader wmsOrderHeader,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                       HttpServletRequest req) {
        QueryWrapper<WmsOrderHeader> queryWrapper = QueryGenerator.initQueryWrapper(wmsOrderHeader, req.getParameterMap());
        Page<WmsOrderHeader> page = new Page<WmsOrderHeader>(pageNo, pageSize);
        IPage<WmsOrderHeader> pageList = wmsOrderHeaderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param wmsOrderHeaderPage
     * @return
     */
    @AutoLog(value = "入库单主表-添加")
    @ApiOperation(value = "入库单主表-添加", notes = "入库单主表-添加")
    @RequiresPermissions("inOrder:wms_order_header:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody WmsOrderHeaderPage wmsOrderHeaderPage) {
        List<WmsOrderLine> wmsOrderLineList = wmsOrderHeaderPage.getWmsOrderLineList();
        if (CollUtil.isEmpty(wmsOrderLineList)){
            throw new JeecgBootException("明细行不能为空");
        }
        WmsOrderHeader wmsOrderHeader = new WmsOrderHeader();
        BeanUtils.copyProperties(wmsOrderHeaderPage, wmsOrderHeader);
        wmsOrderHeaderService.saveWmsOrderHeader(wmsOrderHeader, wmsOrderHeaderPage.getWmsOrderLineList());
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param wmsOrderHeaderPage
     * @return
     */
    @AutoLog(value = "入库单主表-编辑")
    @ApiOperation(value = "入库单主表-编辑", notes = "入库单主表-编辑")
    @RequiresPermissions("inOrder:wms_order_header:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody WmsOrderHeaderPage wmsOrderHeaderPage) {
        WmsOrderHeader wmsOrderHeader = new WmsOrderHeader();
        BeanUtils.copyProperties(wmsOrderHeaderPage, wmsOrderHeader);
        WmsOrderHeader wmsOrderHeaderEntity = wmsOrderHeaderService.getById(wmsOrderHeader.getId());
        if (wmsOrderHeaderEntity == null) {
            return Result.error("未找到对应数据");
        }
        if (!wmsOrderHeaderEntity.getOrderStatus().equals(CommonWms.WAIT_FOR_CHECK)){
            throw new JeecgBootException("单据状态是"+wmsOrderHeaderEntity.getOrderStatus()+"，不可以编辑");
        }
        wmsOrderHeader.setOrderNum(wmsOrderHeaderEntity.getOrderNum());
        wmsOrderHeaderService.updateMain(wmsOrderHeader, wmsOrderHeaderPage.getWmsOrderLineList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "入库单主表-通过id删除")
    @ApiOperation(value = "入库单主表-通过id删除", notes = "入库单主表-通过id删除")
    @RequiresPermissions("inOrder:wms_order_header:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        WmsOrderHeader wmsOrderHeaderEntity = wmsOrderHeaderService.getById(id);
        if (!wmsOrderHeaderEntity.getOrderStatus().equals(CommonWms.WAIT_FOR_CHECK)){
            throw new JeecgBootException("单据状态是"+wmsOrderHeaderEntity.getOrderStatus()+"，不可以删除");
        }
        wmsOrderHeaderService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "入库单主表-批量删除")
    @ApiOperation(value = "入库单主表-批量删除", notes = "入库单主表-批量删除")
    @RequiresPermissions("inOrder:wms_order_header:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.wmsOrderHeaderService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "入库单主表-通过id查询")
    @ApiOperation(value = "入库单主表-通过id查询", notes = "入库单主表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<WmsOrderHeader> queryById(@RequestParam(name = "id", required = true) String id) {
        WmsOrderHeader wmsOrderHeader = wmsOrderHeaderService.getById(id);
        if (wmsOrderHeader == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(wmsOrderHeader);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "入库单子表-通过主表ID查询")
    @ApiOperation(value = "入库单子表-通过主表ID查询", notes = "入库单子表-通过主表ID查询")
    @GetMapping(value = "/queryWmsOrderLineByMainId")
    public Result<IPage<WmsOrderLine>> queryWmsOrderLineListByMainId(@RequestParam(name = "id", required = true) String id) {
        WmsOrderHeader wmsOrderHeader = wmsOrderHeaderService.getById(id);
        List<WmsOrderLine> wmsOrderLineList = wmsOrderLineService.selectByMainId(wmsOrderHeader.getOrderNum());
        IPage<WmsOrderLine> page = new Page<>();
        page.setRecords(wmsOrderLineList);
        page.setTotal(wmsOrderLineList.size());
        return Result.OK(page);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param wmsOrderHeader
     */
    @RequiresPermissions("inOrder:wms_order_header:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WmsOrderHeader wmsOrderHeader) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<WmsOrderHeader> queryWrapper = QueryGenerator.initQueryWrapper(wmsOrderHeader, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        //Step.2 获取导出数据
        List<WmsOrderHeader> wmsOrderHeaderList = wmsOrderHeaderService.list(queryWrapper);

        // Step.3 组装pageList
        List<WmsOrderHeaderPage> pageList = new ArrayList<WmsOrderHeaderPage>();
        for (WmsOrderHeader main : wmsOrderHeaderList) {
            WmsOrderHeaderPage vo = new WmsOrderHeaderPage();
            BeanUtils.copyProperties(main, vo);
            List<WmsOrderLine> wmsOrderLineList = wmsOrderLineService.selectByMainId(main.getId());
            vo.setWmsOrderLineList(wmsOrderLineList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "入库单主表列表");
        mv.addObject(NormalExcelConstants.CLASS, WmsOrderHeaderPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("入库单主表数据", "导出人:" + sysUser.getRealname(), "入库单主表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("inOrder:wms_order_header:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<WmsOrderHeaderPage> list = ExcelImportUtil.importExcel(file.getInputStream(), WmsOrderHeaderPage.class, params);
                for (WmsOrderHeaderPage page : list) {
                    WmsOrderHeader po = new WmsOrderHeader();
                    BeanUtils.copyProperties(page, po);
                    wmsOrderHeaderService.saveMain(po, page.getWmsOrderLineList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    //--------------------------------质量检验开始--------------------------------------
    //@AutoLog(value = "质量检验-分页列表查询")
    @ApiOperation(value = "质量检验-分页列表查询", notes = "质量检验-分页列表查询")
    @GetMapping(value = "/inOrderLineList")
    public Result<IPage<WmsOrderLine>> inOrderLineList(WmsOrderLine wmsOrderLine,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        QueryWrapper<WmsOrderLine> queryWrapper = QueryGenerator.initQueryWrapper(wmsOrderLine, req.getParameterMap());
        queryWrapper.in("line_status", CommonWms.WAIT_FOR_CHECK,CommonWms.BEGIN_FOR_CHECK);
        Page<WmsOrderLine> page = new Page<WmsOrderLine>(pageNo, pageSize);
        IPage<WmsOrderLine> pageList = wmsOrderLineService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    //@AutoLog(value = "质量检验-通过id查询")
    @ApiOperation(value="质量检验-通过id查询", notes="质量检验-通过id查询")
    @GetMapping(value = "/inOrderLineQueryById")
    public Result<WmsOrderLine> inOrderLineQueryById(@RequestParam(name="id",required=true) String id) {
        WmsOrderLine wmsOrderLine = wmsOrderLineService.getById(id);
        if(wmsOrderLine==null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(wmsOrderLine);
    }

    //@AutoLog(value = "质量检验验收")
    @ApiOperation(value="质量检验-质量检验验收", notes="质量检验-质量检验验收")
    @RequestMapping(value = "/qualityInspec", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<WmsOrderLine> qualityInspec(@RequestBody WmsOrderLine wmsOrderLinevo) {
        WmsOrderLine wmsOrderLine = wmsOrderLineService.getById(wmsOrderLinevo.getId());
        if(wmsOrderLine==null) {
            return Result.error("未找到对应数据");
        }
        if (!NumberUtil.isNumber(wmsOrderLinevo.getGoodsYsCount())){
            throw new JeecgBootException("验收数量填写有误");
        }
        wmsOrderLineService.qualityInspec(wmsOrderLinevo);
        return Result.OK("检验成功!");
    }

    //--------------------------------质量检验结束--------------------------------------

}


